package com.mj.mafeed.service;

import org.codehaus.jackson.map.ObjectMapper;

import com.mj.mafeed.bean.ReceiverJSON;
import com.mj.mafeed.bean.ReceiverListJSON;
import com.mj.mafeed.config.Constants;
import com.mj.mafeed.util.HttpUtils;

/**
 * 收货地址
 * @author zhaominglei
 * @date 2014-12-17
 * 
 */
public class ReceiverService extends BaseService {
	/**
	 * 收货地址列表
	 */
	public ReceiverListJSON getReceiver(String referer, String username, String sign) {
		StringBuilder url = new StringBuilder(Constants.MEMBER_RECEIVER_URL);
		url.append("?username=").append(username).append("&sign=").append(sign);
		String result = HttpUtils.doGet(url.toString());
		if (result != null && !result.equals("")) {
			try {
				ReceiverListJSON receiverList = new ObjectMapper().readValue(result, ReceiverListJSON.class);
				return (receiverList != null) ? receiverList : null; 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 保存收货地址
	 */
	public boolean saveReceiver(ReceiverJSON receiverJSON, String referer, String username, String sign) {
		StringBuilder url = new StringBuilder();
		StringBuilder param = new StringBuilder();
		param.append("address=").append(receiverJSON.getAddress()).append("&consignee=").append(receiverJSON.getConsignee());
		param.append("&isDefault=").append(receiverJSON.getIsDefault()).append("&phone=").append(receiverJSON.getPhone());
		param.append("&zipCode=").append(receiverJSON.getZipCode()).append("&areaId=").append(receiverJSON.getAreaId());
		if (receiverJSON.getReceiverId() != null && receiverJSON.getReceiverId() > 0l) {
			url.append(Constants.MEMBER_RECEIVER_UPDATE_URL);
			param.append("&receiverId=").append(receiverJSON.getReceiverId());
		} else {
			url.append(Constants.MEMBER_RECEIVER_ADD_URL);
		}
		param.append("&username=").append(username).append("&sign=").append(sign);
		String result = HttpUtils.doPost(url.toString(), param.toString());
		if (result != null && !result.equals("")) {
			if (result.equals("true")) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 获取默认收货地址
	 */
	public ReceiverJSON getdefault(String referer, String username, String sign) {
		StringBuilder url = new StringBuilder(Constants.MEMBER_DEFAULT_RECEIVER_URL);
		url.append("?username=").append(username).append("&sign=").append(sign);
		String result = HttpUtils.doGet(url.toString());
		if (result != null && !result.equals("")) {
			try {
				ReceiverJSON receiverJSON = new ObjectMapper().readValue(result, ReceiverJSON.class);
				return (receiverJSON != null) ? receiverJSON : null; 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
